package com.schoolhelper.social.service.impl;

import com.schoolhelper.social.domain.Message;
import com.schoolhelper.social.mapper.MessageMapper;
import com.schoolhelper.social.service.MessageService;
import com.schoolhelper.config.FileUploadConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.Map;

@Service
public class MessageServiceImpl implements MessageService {
    
    private static final Logger logger = LoggerFactory.getLogger(MessageServiceImpl.class);
    
    @Autowired
    private MessageMapper messageMapper;
    
    @Autowired
    private FileUploadConfig fileUploadConfig;
    
    @Override
    public boolean sendMessage(Message message) {
        try {
            int result = messageMapper.insertMessage(message);
            return result > 0;
        } catch (Exception e) {
            logger.error("发送消息失败", e);
            return false;
        }
    }
    
    @Override
    public List<Message> getChatHistory(Long userId1, Long userId2, int page, int size) {
        try {
            int offset = (page - 1) * size;
            List<Message> messages = messageMapper.getChatHistory(userId1, userId2, size, offset);
            
            // 处理头像URL
            for (Message message : messages) {
                if (message.getSenderAvatar() != null && !message.getSenderAvatar().isEmpty() 
                    && !message.getSenderAvatar().startsWith("http")) {
                    message.setSenderAvatar(fileUploadConfig.getFileUrl(message.getSenderAvatar()));
                }
                if (message.getReceiverAvatar() != null && !message.getReceiverAvatar().isEmpty() 
                    && !message.getReceiverAvatar().startsWith("http")) {
                    message.setReceiverAvatar(fileUploadConfig.getFileUrl(message.getReceiverAvatar()));
                }
            }
            
            return messages;
        } catch (Exception e) {
            logger.error("获取聊天记录失败", e);
            throw new RuntimeException("获取聊天记录失败", e);
        }
    }
    
    @Override
    public List<Map<String, Object>> getChatList(Long userId) {
        try {
            List<Map<String, Object>> chatList = messageMapper.getChatList(userId);
            
            // 处理头像URL
            for (Map<String, Object> chat : chatList) {
                String avatar = (String) chat.get("chat_avatar");
                if (avatar != null && !avatar.isEmpty() && !avatar.startsWith("http")) {
                    chat.put("chat_avatar", fileUploadConfig.getFileUrl(avatar));
                }
            }
            
            return chatList;
        } catch (Exception e) {
            logger.error("获取聊天列表失败", e);
            throw new RuntimeException("获取聊天列表失败", e);
        }
    }
    
    @Override
    public int getUnreadCount(Long userId) {
        try {
            return messageMapper.getUnreadCount(userId);
        } catch (Exception e) {
            logger.error("获取未读消息数量失败", e);
            return 0;
        }
    }
    
    @Override
    public List<Map<String, Object>> getUnreadMessageDetails(Long userId) {
        try {
            List<Map<String, Object>> unreadDetails = messageMapper.getUnreadMessageDetails(userId);
            
            // 处理头像URL
            for (Map<String, Object> detail : unreadDetails) {
                String avatar = (String) detail.get("sender_avatar");
                if (avatar != null && !avatar.isEmpty() && !avatar.startsWith("http")) {
                    detail.put("sender_avatar", fileUploadConfig.getFileUrl(avatar));
                }
            }
            
            return unreadDetails;
        } catch (Exception e) {
            logger.error("获取未读消息详情失败", e);
            throw new RuntimeException("获取未读消息详情失败", e);
        }
    }
    
    @Override
    public void markMessagesAsRead(Long senderId, Long receiverId) {
        try {
            messageMapper.markMessagesAsRead(senderId, receiverId);
        } catch (Exception e) {
            logger.error("标记消息已读失败", e);
        }
    }
    
    @Override
    public int getMessageCountBetweenUsers(Long userId1, Long userId2) {
        try {
            return messageMapper.getMessageCountBetweenUsers(userId1, userId2);
        } catch (Exception e) {
            logger.error("获取用户间消息数量失败", e);
            return 0;
        }
    }
}